package com.chx.usersdemo.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chx.usersdemo.common.QueryPageParam;
import com.chx.usersdemo.common.Result;
import com.chx.usersdemo.entity.Users;
import com.chx.usersdemo.mapper.UsersMapper;
import com.chx.usersdemo.service.UsersService;
import com.chx.usersdemo.utils.ExcelExporter;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chx
 * @since 2025-03-04
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    @Autowired
    UsersMapper usersMapper;


    @GetMapping("/list")
    public List<Users> list(){
        return usersService.list();
    }
    //新增
    @PostMapping("/save")
    public Result save(@RequestBody Users user){
        return usersService.save(user)?Result.suc():Result.fail();
    }
    @PostMapping("/update")
    public Result update(@RequestBody Users user){
        return usersService.updateById(user)?Result.suc():Result.fail();
    }
    //修改
    @PostMapping("/mod")
    public boolean mod(@RequestBody Users user){
        return usersService.updateById(user);
    }
    //新增或修改
    @PostMapping("saveOrMod")
    public boolean saveOrMod(@RequestBody Users user){
        return usersService.saveOrUpdate(user);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("/del")
    public Result del(@RequestParam String  id){
        return usersService.removeById(id)?Result.suc():Result.fail();
    }
    @GetMapping("/delByIds")
    public Result delByIds(@RequestParam List ids){
        return usersService.removeByIds(ids)?Result.suc():Result.fail();
    }
    @GetMapping("/delete")
    //删除
    public boolean delete(Integer id){
        return usersService.removeById(id);
    }
    //查询
    @PostMapping("/listP")
    public Result listP(@RequestBody Users user){
        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(user.getName())){

            lambdaQueryWrapper.like(Users::getName,user.getName());
        }
        return Result.suc(usersService.list(lambdaQueryWrapper));

    }
    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query){
        /*LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(Users::getName,user.getName());
        return usersService.list(lambdaQueryWrapper);*/
        HashMap param = query.getParam();
        String name = (String)param.get("name");


        Page<Users> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotBlank(name) && !"null".equals(name) ){
            lambdaQueryWrapper.like(Users::getName,name);
        }
        IPage result =  usersService.page(page,lambdaQueryWrapper);
        System.out.println(result.getTotal());
        return Result.suc(result.getRecords(),result.getTotal());

    }

    /**
     * 分页查询
     * @param query
     * @return
     */
    @PostMapping("/listPageC")
    public Result listPageC(@RequestBody QueryPageParam query){
        /*LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(Users::getName,user.getName());
        return usersService.list(lambdaQueryWrapper);*/
        HashMap param = query.getParam();
        String name = (String)param.get("name");


        Page<Users> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

       /* LambdaQueryWrapper<Users> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.like(Users::getName,name);*/

        IPage result =  usersService.pageC(page);
        System.out.println(result.getTotal());
        return Result.suc(result.getRecords(),result.getTotal());
    }
    /**
     * 导出功能
     */
    /* public static void reflectExport(OutputStream outputStream,List<String> clumList,List dataList) throws IllegalAccessException {

         List<List<String>> allList = new ArrayList<>();

         if(ObjectUtils.isEmpty(dataList)){
                return;
         }
         //获取class文件
         Class<?> aClass = dataList.get(0).getClass();
         //获取class对象属性
         Field[] fields = aClass.getDeclaredFields();
         for (int i = 0; i < dataList.size(); i++) {
             List<String> list = new ArrayList<>();
             for (int j = 0; j < fields.length; j++) {
                 Object obj = fields[j].get(dataList.get(i));
                 if(obj != null){
                     list.add(obj.toString());
                 }
             }
         }
         ExcelExporter exporter = new ExcelExporter();


     }*/
    /**
     * 导出
     */
    @GetMapping("/exportO")
    public Result export(HttpServletResponse servletResponse) throws IOException {
        List<Users> list = usersMapper.selectListAll(new QueryWrapper<>());
        ExcelWriter write = ExcelUtil.getWriter().write(list, true);
        servletResponse.setHeader("Content-Disposition","attachment;filename=Text.xls ");
        ServletOutputStream outputStream = servletResponse.getOutputStream();
        write.flush(outputStream);
        outputStream.close();
        write.close();
        return Result.suc();
    }
   /* @GetMapping("/exporta")
    public void exporta() throws IOException {
        List<List<Object>> data = new ArrayList<>();
        // 添加数据到data列表...

        String filePath = "output.xlsx";
        try {
            ExcelExporter.exportToExcel(data, filePath);
            System.out.println("导出成功！");
        } catch (IOException e) {
            System.err.println("导出发生错误: " + e.getMessage());
        }

    }*/
}
